//
//  DHS2_HomeViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/4/12.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHS2_HomeViewController.h"
#import "DHSpecialEditionCell.h"
#import "DHHomeActivityCell.h"
#import "DHHomeLabelCell.h"
#import "DHHomeRecommendCell.h"
#import "DHHomeCouponCell.h"
#import "DHRank&CommentTableViewCell.h"
#import "DHHomeMagazineCell.h"
#import "DHFeaturedCell.h"
#import "DHHomeCategoriesCell.h"
#import "DHHomeCommentsCell.h"
#import "DHHomeHotBrandsCell.h"
#import "ZPRightImageButton.h"
#import "DHCityListViewController.h"
#import "DHLoginGenderViewController.h"
#import "DHHomeGuessCell.h"

@interface DHS2_HomeViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) UITableView *tableView; //内容

@property (strong, nonatomic) NSArray *specialsArray; //本月特辑数据
@property (strong, nonatomic) NSArray *campaignsArray; //最新活动
@property (strong, nonatomic) NSArray *labelsArray; //热门标签
@property (strong, nonatomic) NSArray *recommend_productsArray; //推荐服饰
@property (strong, nonatomic) NSArray *promotionsArray; //优惠券
@property (strong, nonatomic) NSArray *social_rankArray; //用户穿搭排名点评
@property (strong, nonatomic) NSArray *articlesArray; //杂志
@property (strong, nonatomic) NSArray *dresshereArray; //DRESSHERE精选
@property (strong, nonatomic) NSArray *categoriesArray; //热门分类
@property (strong, nonatomic) NSArray *dianpingArray; //大咖点评
@property (strong, nonatomic) NSArray *brandsArray; //热门品牌
@property (strong, nonatomic) NSMutableArray *guessArray; //猜你喜欢

@property (assign, nonatomic) NSInteger guessPageIndex;

@property (strong, nonatomic) ZPRightImageButton *cityButton;

@property (strong, nonatomic) NSString *categorySex;

@end

@implementation DHS2_HomeViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    
    // 用户未登录，且未选别性别的情况下
    if (![Login isLogin]) {
        self.tableView.mj_footer.hidden = YES;
        
        if (![[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_SEX]) {
            DHLoginGenderViewController *genderController = [[DHLoginGenderViewController alloc] init];
            [self presentViewController:genderController animated:YES completion:nil];
        }
    }else{
        self.tableView.mj_footer.hidden = NO;
    }
    
    
//    [self requestData];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
//    [self.tableView reloadData];
    
    if ([Login isLogin]) {
        [[GlobalManager shareGlobalManager] refreshVIPInfoAndBlock:^(id data, NSError *error) {
            
        }];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.guessPageIndex = 0;
    
    self.categorySex = [GlobalManager shareGlobalManager].user.sex? :[[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_SEX];
    
    //设置导航栏title图片
    [self.navigationView setTitleWithImage:[UIImage imageNamed:@"Dresshere"]];
    //城市按钮
    self.cityButton = [[ZPRightImageButton alloc] initWithFrame:CGRectMake(kScreenWidth/2 + 58, self.navigationView.height - 44, 60, 44) title:@"北京" titleFont:[UIFont systemFontOfSize:14] titleColor:[UIColor colorWithHexString:@"#4C4D5C"] image:[UIImage imageNamed:@"arrow_down.png"] buttonBackgroundColor:[UIColor clearColor]];
    [self.navigationView addSubview:self.cityButton];
    
    WeakSelf(weakSelf)
    [self.cityButton bk_addEventHandler:^(id sender) {
        DHCityListViewController *cityListVC = [[DHCityListViewController alloc] init];
        [weakSelf presentViewController:cityListVC animated:YES completion:nil];
    } forControlEvents:UIControlEventTouchUpInside];
    
    //创建tableview
    CGFloat tableViewH = kScreenHeight - self.navigationView.height;
    if (iPhoneX) {
        tableViewH = kScreenHeight - self.navigationView.height - 20 - 40;
    }
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navigationView.bottom, kScreenWidth, tableViewH)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DHSpecialEditionCell" bundle:nil] forCellReuseIdentifier:kDHSpecialEditionCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHHomeActivityCell" bundle:nil] forCellReuseIdentifier:kDHHomeActivityCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHHomeLabelCell" bundle:nil] forCellReuseIdentifier:kDHHomeLabelCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHHomeRecommendCell" bundle:nil] forCellReuseIdentifier:kDHHomeRecommendCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHHomeCouponCell" bundle:nil] forCellReuseIdentifier:kDHHomeCouponCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHRank&CommentTableViewCell" bundle:nil] forCellReuseIdentifier:kDHRank_CommentTableViewCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHHomeMagazineCell" bundle:nil] forCellReuseIdentifier:kDHHomeMagazineCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHFeaturedCell" bundle:nil] forCellReuseIdentifier:kDHFeaturedCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHHomeCategoriesCell" bundle:nil] forCellReuseIdentifier:kDHHomeCategoriesCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHHomeCommentsCell" bundle:nil] forCellReuseIdentifier:kDHHomeCommentsCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHHomeHotBrandsCell" bundle:nil] forCellReuseIdentifier:kDHHomeHotBrandsCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHHomeGuessCell" bundle:nil] forCellReuseIdentifier:kDHHomeGuessCell];
    
    self.tableView.mj_header = [DHMJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    self.tableView.mj_footer = [DHMJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreGuess)];
    
    [self requestData];
    
    addNObserver(@selector(city_list_selected:), @"city_list_selected");
    addNObserver(@selector(left_change_sex), @"left_change_sex");
}

- (void)dealloc{
    removeNObserver(@"city_list_selected");
    removeNObserver(@"left_change_sex");
}

- (void)city_list_selected:(NSNotification *)not{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.cityButton changeTitle:[not.object objectForKey:@"city"]];
    });
}

- (void)left_change_sex{
//    NSString *sex = [GlobalManager shareGlobalManager].user.sex;
//    [[DHNetAPIClient shareDHNetAPIClient] request_home_categories_hotWithParams:@{@"sex":sex} andBlock:^(id data, NSError *error) {
//        if (data) {
//            self.categoriesArray = [data objectForKey:@"categories"];
//            [self.tableView reloadRow:8 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
//        }
//    }];
    self.categorySex = [GlobalManager shareGlobalManager].user.sex;
    [self requestData];
}

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    if ([eventName isEqualToString:@"change_dianping"]) {
        [[DHNetAPIClient shareDHNetAPIClient] request_home_social_rankAndBlock:^(id data, NSError *error) {
            if (data) {
                self.social_rankArray = [data objectForKey:@"posts"];
                [self.tableView reloadRow:5 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
    }else if ([eventName isEqualToString:@"man_cagetory"]){
        self.categorySex = @"男";
        [[DHNetAPIClient shareDHNetAPIClient] request_home_categories_hotWithParams:@{@"sex":@"男"} andBlock:^(id data, NSError *error) {
            if (data) {
                self.categoriesArray = [data objectForKey:@"categories"];
                [self.tableView reloadRow:8 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
    }else if ([eventName isEqualToString:@"woman_cagetory"]){
        self.categorySex = @"女";
        [[DHNetAPIClient shareDHNetAPIClient] request_home_categories_hotWithParams:@{@"sex":@"女"} andBlock:^(id data, NSError *error) {
            if (data) {
                self.categoriesArray = [data objectForKey:@"categories"];
                [self.tableView reloadRow:8 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
    }else if ([eventName isEqualToString:@"change_to_brand"]){
        [self.tabBarController setSelectedIndex:1];
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"change_to_brand_home"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

// 加载数据
- (void)requestData{
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
    [self.tableView.mj_header endRefreshing];
    // 获取本页特辑
    [[DHNetAPIClient shareDHNetAPIClient] request_specialsAndBlock:^(id data, NSError *error) {
        if (data) {
            self.specialsArray = [data objectForKey:@"articles"];
            [self.tableView reloadRow:0 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    // 获取最新活动
    [[DHNetAPIClient shareDHNetAPIClient] request_campaignsAndBlock:^(id data, NSError *error) {
        if (data) {
            self.campaignsArray = [data objectForKey:@"campaigns"];
            [self.tableView reloadRow:1 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    // 获取热门标签
    [[DHNetAPIClient shareDHNetAPIClient] request_labelsWithParams:@{@"hot":@(1)} andBlock:^(id data, NSError *error) {
        if (data) {
            self.labelsArray = [data objectForKey:@"labels"];
            [self.tableView reloadRow:2 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    
    //获取推荐服饰
    [[DHNetAPIClient shareDHNetAPIClient] request_recommend_productsAndBlock:^(id data, NSError *error) {
        if (data) {
            self.recommend_productsArray = data;
            [self.tableView reloadRow:3 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    
    //获取可领取优惠券列表
    [[DHNetAPIClient shareDHNetAPIClient] request_promotionsAndBlock:^(id data, NSError *error) {
        if (data) {
            self.promotionsArray = [data objectForKey:@"promotions"];
            [self.tableView reloadRow:4 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    
    //获取首页用户穿搭排名点评
    [[DHNetAPIClient shareDHNetAPIClient] request_home_social_rankAndBlock:^(id data, NSError *error) {
        if (data) {
            self.social_rankArray = [data objectForKey:@"posts"];
            [self.tableView reloadRow:5 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    
    //获取首页杂志专区
    [[DHNetAPIClient shareDHNetAPIClient] request_home_articlesAndBlock:^(id data, NSError *error) {
        if (data) {
            self.articlesArray = [data objectForKey:@"articles"];
            [self.tableView reloadRow:6 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    
    //获取DRESSHERE精选
    [[DHNetAPIClient shareDHNetAPIClient] request_home_products_dresshereAndBlock:^(id data, NSError *error) {
        if (data) {
            self.dresshereArray = [data objectForKey:@"products"];
            [self.tableView reloadRow:7 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    
    //热门分类
    NSString *sex;
    if ([Login isLogin]) {
        sex = [Login curLoginUser].sex;
    }else{
        sex = [[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_SEX];
        if (!sex) {
            sex = @"男";
        }
    }
    [[DHNetAPIClient shareDHNetAPIClient] request_home_categories_hotWithParams:@{@"sex":sex} andBlock:^(id data, NSError *error) {
        if (data) {
            self.categoriesArray = [data objectForKey:@"categories"];
            [self.tableView reloadRow:8 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    
    //大咖点评
    [[DHNetAPIClient shareDHNetAPIClient] request_home_dianpingAndBlock:^(id data, NSError *error) {
        if (data) {
            self.dianpingArray = [data objectForKey:@"dianpings"];
            [self.tableView reloadRow:9 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    
    //热门品牌
    [[DHNetAPIClient shareDHNetAPIClient] request_brands_hotWithParams:@{} AndBlock:^(id data, NSError *error) {
        if (data) {
            self.brandsArray = [data objectForKey:@"brands"];
            [self.tableView reloadRow:10 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    
    //猜你喜欢
    self.guessPageIndex = 0;
    if ([Login isLogin]) {
        [self.guessArray removeAllObjects];
        [[DHNetAPIClient shareDHNetAPIClient] request_products_guessyoulikeParams:@{@"pageIndex":@(0),@"pageSize":@(20)} andBlock:^(id data, NSError *error) {
            [self.guessArray addObjectsFromArray:[data objectForKey:@"products"]];
            [self.tableView reloadRow:11 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
            self.guessPageIndex += 1;
        }];
    }
}

- (void)loadMoreGuess{
//    //猜你喜欢
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
    if ([Login isLogin]) {
        [[DHNetAPIClient shareDHNetAPIClient] request_products_guessyoulikeParams:@{@"pageIndex":@(self.guessPageIndex),@"pageSize":@(20)} andBlock:^(id data, NSError *error) {
            [self.tableView.mj_footer endRefreshing];
            [self.guessArray addObjectsFromArray:[data objectForKey:@"products"]];
            [self.tableView reloadRow:11 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
            self.guessPageIndex += 1;
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate and UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 12;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:{
            return kScreenWidth / 1.275;
        }
        case 1:{
            return 186;
        }
        case 2:{
            return 110;
        }
        case 3:{
            CGFloat w = (kScreenWidth - 24) / 2;
            CGFloat h = w * 1.29 + 61;
            if (self.recommend_productsArray.count % 2 ==0) {
                return 78 + (self.recommend_productsArray.count / 2) * h;
            }else{
                return 78 + (self.recommend_productsArray.count / 2 + 1) * h;
            }
        }
        case 4:{
            if (self.promotionsArray.count == 0) {
                return 0;
            }else{
                return 100;
            }
        }
        case 5:{
            return 0;
        }
        case 6:{
            __block int large = 0;
            __block int normal = 0;
            [self.articlesArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([[obj objectForKey:@"layout"] isEqualToString:@"大矩形"]) {
                    large += 1;
                }else{
                    normal += 1;
                }
            }];
            return 92.5 + 210 * large + 100 * normal;
        }
        case 7:{
            NSInteger count = self.dresshereArray.count;
            if (count == 0) {
                return 232;
            }else if (count > 0 && count <= 3) {
                return 232 + 190;
            }else if (count >3 && count <= 6){
                return 232 + 190 * 2;
            }else{
                return 232 + 190 * 3;
            }
        }
        case 8:{
            if (self.categoriesArray.count % 3 == 0) {
                return 155 + (self.categoriesArray.count / 3) * 100;
            }else{
                return 155 + (self.categoriesArray.count / 3 + 1) * 100;
            }
        }
        case 9:{
            if (self.dianpingArray.count > 0) {
                return 95 + self.dianpingArray.count * 95;
            }else{
                return 0;
            }
        }
        case 10:{
            CGFloat w = (kScreenWidth - 32) / 3;
            CGFloat h = w * 0.51;
            if (self.brandsArray.count % 3 == 0) {
                return 87 + (self.brandsArray.count / 3) * h;
            }else{
                return 87 + (self.brandsArray.count / 3 + 1) * h;
            }
        }
        case 11:{
            if (self.guessArray.count > 0) {
                CGFloat w = (kScreenWidth - 24) / 2;
                CGFloat h = w * 1.29 + 61;
                if (self.guessArray.count % 2 ==0) {
                    return 78 + (self.guessArray.count / 2) * h;
                }else{
                    return 78 + (self.guessArray.count / 2 + 1) * h;
                }
            }else{
                return 0;
            }
        }
        default:{
            return 50;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        DHSpecialEditionCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHSpecialEditionCell forIndexPath:indexPath];
        [cell updateCellWithArray:self.specialsArray];
        return cell;
    }else if (indexPath.row == 1){
        DHHomeActivityCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHHomeActivityCell forIndexPath:indexPath];
        [cell updateCellWithArray:self.campaignsArray];
        return cell;
    }else if (indexPath.row == 2){
        DHHomeLabelCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHHomeLabelCell forIndexPath:indexPath];
        [cell updateCellWithArray:self.labelsArray];
        return cell;
    }else if (indexPath.row == 3){ //推荐服饰
        DHHomeRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHHomeRecommendCell forIndexPath:indexPath];
        [cell updateCellWithArray:self.recommend_productsArray];
        return cell;
    }else if (indexPath.row == 4){
        DHHomeCouponCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHHomeCouponCell forIndexPath:indexPath];
        [cell updateCellWithArray:self.promotionsArray];
        if (self.promotionsArray.count == 0) {
            cell.contentView.hidden = YES;
        }else{
            cell.contentView.hidden = NO;
        }
        return cell;
    }else if (indexPath.row == 5){ //穿搭排名点评
        DHRank_CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHRank_CommentTableViewCell forIndexPath:indexPath];
//        [cell updateCellWithArray:self.social_rankArray];
        cell.contentView.hidden = YES;
        return cell;
    }else if (indexPath.row == 6){ // 杂志专区
        DHHomeMagazineCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHHomeMagazineCell forIndexPath:indexPath];
        [cell updateCellWithArray:self.articlesArray];
        return cell;
    }else if (indexPath.row == 7){// DRESSHERE精选
        DHFeaturedCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHFeaturedCell forIndexPath:indexPath];
        [cell updateCellWithArray:self.dresshereArray];
        return cell;
    }else if (indexPath.row == 8){
        DHHomeCategoriesCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHHomeCategoriesCell forIndexPath:indexPath];
        if ([self.categorySex isEqualToString:@"男"]) {
            [cell.manImgView setImage:[UIImage imageNamed:@"home_category_selected"]];
            [cell.womanImgView setImage:[UIImage imageNamed:@"home_category_unselected"]];
        }else{
            [cell.manImgView setImage:[UIImage imageNamed:@"home_category_unselected"]];
            [cell.womanImgView setImage:[UIImage imageNamed:@"home_category_selected"]];
        }
        [cell updateCellWithArray:self.categoriesArray];
        return cell;
    }else if (indexPath.row == 9){
        DHHomeCommentsCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHHomeCommentsCell forIndexPath:indexPath];
        [cell updateCellWithArray:self.dianpingArray];
        if (self.dianpingArray.count == 0) {
            cell.contentView.hidden = YES;
        }else{
            cell.contentView.hidden = NO;
        }
        return cell;
    }else if (indexPath.row == 10){
        DHHomeHotBrandsCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHHomeHotBrandsCell forIndexPath:indexPath];
        [cell updateCellWithArray:self.brandsArray];
        return cell;
    }else if (indexPath.row == 11){
        DHHomeGuessCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHHomeGuessCell forIndexPath:indexPath];
        [cell updateCellWithArray:self.guessArray];
        if (self.guessArray.count > 0) {
            cell.contentView.hidden = NO;
        }else{
            cell.contentView.hidden = YES;
        }
        return cell;
    }else{
        return nil;
    }
}

#pragma mark - 初始化数组
- (NSArray *)specialsArray{
    if (!_specialsArray) {
        _specialsArray = [NSArray array];
    }
    return _specialsArray;
}

- (NSArray *)campaignsArray{
    if (!_campaignsArray) {
        _campaignsArray = [NSArray array];
    }
    return _campaignsArray;
}

- (NSArray *)labelsArray{
    if (!_labelsArray) {
        _labelsArray = [NSArray array];
    }
    return _labelsArray;
}

- (NSArray *)recommend_productsArray{
    if (!_recommend_productsArray) {
        _recommend_productsArray = [NSArray array];
    }
    return _recommend_productsArray;
}

- (NSArray *)promotionsArray{
    if (!_promotionsArray) {
        _promotionsArray = [NSArray array];
    }
    return _promotionsArray;
}

- (NSArray *)social_rankArray{
    if (!_social_rankArray) {
        _social_rankArray = [NSArray array];
    }
    return _social_rankArray;
}

- (NSArray *)articlesArray{
    if (!_articlesArray) {
        _articlesArray = [NSArray array];
    }
    return _articlesArray;
}

- (NSArray *)dresshereArray{
    if (!_dresshereArray) {
        _dresshereArray = [NSArray array];
    }
    return _dresshereArray;
}

- (NSArray *)categoriesArray{
    if (!_categoriesArray) {
        _categoriesArray = [NSArray array];
    }
    return _categoriesArray;
}

- (NSArray *)brandsArray{
    if (!_brandsArray) {
        _brandsArray = [NSArray array];
    }
    return _brandsArray;
}

- (NSMutableArray *)guessArray{
    if (!_guessArray) {
        _guessArray = [NSMutableArray array];
    }
    return _guessArray;
}

@end
